﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GDBLL.Engine.Charactor
{
    /// <summary>
    /// Dictionay作为Charactor数据仓库
    /// </summary>
    public class InDictionaryCharactorProvider : ICharactorProvider
    {
        private int m_charactorDicCount;
        private int m_curCharactorDic = 0;
        private Dictionary<int, object>[] m_charactorDic;
        private object m_state = new object();

        public InDictionaryCharactorProvider(int count)
        {
            if (count <= 0)
                throw new ArgumentOutOfRangeException("count");

            this.m_charactorDicCount = count;
            this.m_charactorDic = new Dictionary<int, object>[this.m_charactorDicCount];
        }

        public InDictionaryCharactorProvider()
            : this(5) 
        { }

        public void InitializeCharactorClient(int privateToken)
        {
            if (privateToken<0)
                throw new ArgumentNullException("charactorClient");

            lock (m_state)//TODO:登录势必会慢～
            {
                bool isExist = false;
                for (int i = 0; i < this.m_charactorDicCount; i++)
                {
                    if (this.m_charactorDic[i].ContainsKey(privateToken))
                    {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist)
                {

                    CharactorClient charactorClient = new CharactorClient(privateToken);



                    //所在的dictionary
                    charactorClient.Datahouseid = this.m_curCharactorDic;

                    this.m_charactorDic[this.m_curCharactorDic].Add(charactorClient.PrivateToken, charactorClient);

                    this.m_curCharactorDic++;

                    if (this.m_curCharactorDic >= this.m_charactorDicCount)
                        this.m_curCharactorDic = 0; //  cycle back to 0
                }
                
            }

            //  ok, they are in there ready to be used
        }

        public CharactorClient GetCharactorClient(int privateToken, int cur)
        {
            if(!this.m_charactorDic[cur].ContainsKey(privateToken))
                throw new ArgumentNullException("PrivateToken不存在");

            //  return the client private token
            return (CharactorClient)this.m_charactorDic[cur][privateToken];
        }

        public CharactorClient GetCharactorClient(int privateToken)
        {
            throw new NotImplementedException();
        }

    }
}
